/*
 * Copyright 2013 - 2020 Outworkers Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.outworkers.phantom.database

import com.outworkers.phantom.PhantomBaseSuite
import com.outworkers.phantom.dsl._
import com.outworkers.phantom.tables.bugs.SecondaryIndexItem
import com.outworkers.phantom.tables.dbs.SecondaryIndexOnlyDatabase
import com.outworkers.util.samplers._
import org.scalatest.FlatSpec

class DatabaseInitialisationTests extends FlatSpec
  with PhantomBaseSuite
  with SecondaryIndexOnlyDatabase.connector.Connector {

  val specialDb = SecondaryIndexOnlyDatabase

  override def beforeAll(): Unit = {
    super.beforeAll()
    val _ = specialDb.create()
  }

  it should "automatically initialise Secondary Indexes" in {
    val sample = gen[SecondaryIndexItem]

    val chain = for {
      _ <- specialDb.schemaBugSecondaryIndex.store(sample).future()
      res <- specialDb.schemaBugSecondaryIndex.select.where(_.ref eqs sample.ref).one()
    } yield res

    whenReady(chain) { res =>
      info("Querying by the secondary index should return the record")
      res.value shouldEqual sample
    }
  }
}
